/**
 * @description global permission directive
 * @example v-permission="['admin']"
 * @author Zhangbin
 */

import { Directive } from 'vue'
import store from '@/store'
const { getters } = store;

export const permission: Directive = {
  mounted(el: HTMLElement, binding, vnode) {
    const { value } = binding;
    const roles = getters?.userInfo?.roles ?? [];

    if (value?.length) {
      const permissionRoles = value;
      const hasPermission = roles.some((role: string) => {
        return permissionRoles.includes(role)
      });

      if (!hasPermission) {
        el.parentNode?.removeChild(el)
      }
    } else {
      throw new Error(`need roles!`)
    }
  }
}